<?php
/**
 * Created by JetBrains PhpStorm.
 * User: huan
 * Date: 14-3-21
 * Time: 上午9:24
 * To change this template use File | Settings | File Templates.
 */

/**
 * 京东搜索
 * Class JdSearch
 */
class JdSearch {

    public $item_id     = 0;
    public $keyWords    = '';
    public $cCurl       = null;
    public $page        = 1;
    public $content     = '';
    //最大查询页
    public $search_max_page = 5;
    //每页共36个商品 4*9
    public $page_item_size  = 36;


    function __construct($item_id,$keywords){
        $this->item_id  = $item_id;
        $this->keyWords = $keywords;
        $this->cCurl  = new Curl();
    }

    /**
     * 搜索后得到的结果
     * @return mixed
     */
    function search_content(){

        $url = $this->search_url();

        cli_out('search_url:'.$url);

        $response = $this->cCurl->get($url);

        if(!empty($response) && isset($response['header']['http_code'])){
            $http_code = $response['header']['http_code'];
            if($http_code == 200){
                $this->content = $response['content'];
            }
        }else{
            $this->content = false;
        }
        return $this->content;
    }

    /**
     * 分页获取排名
     * @return int|mixed
     */
    function get_rank(){

        $rank = 0;
        for($i = 1;$i <= $this->search_max_page;$i++){

            $this->page = $i;

            cli_out('page:'.$this->page);

            //获取内容
            $this->search_content();

            if($this->content){

                $rank = $this->get_rank_from_content();
                if($rank > 0){
                    //分页的排名
                    $rank = ($this->page - 1) * $this->page_item_size + $rank;
                    break;
                }
            }
        }

        return $rank;
    }

    /**
     * 从内容中获取排名
     * @param $item_id
     * @param $content
     * @return int|mixed
     */
    function get_rank_from_content(){

        $reg = '/<li sku="(\\d+)"\s?>/i';
        preg_match_all($reg,$this->content,$matches);

        cli_out('matches:');

        print_r($matches);

        $rank = 0;
        if(isset($matches[1]) && !empty($matches[1])){
            $key = array_search($this->item_id,$matches[1]);

            if(!empty($key)){
                //索引从0开始
                $rank = $key + 1;
            }
        }

        return $rank;
    }

    /**
     * 创建搜索链接
     * @param $keywords
     * @param int $page
     * @return string
     */
    function search_url(){
        return "http://search.jd.com/Search?keyword=".urlencode($this->keyWords)."&enc=utf-8&page=".$this->page;
    }
}